﻿using MatlabWork.Dal;
using MatlabWork.Entity;
using MatlabWork.Model;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using Newtonsoft.Json;
using Prism.Events;
using System.Windows.Data;
using TestingPlatForm.MissionContrl.Models;
using TestingPlatForm.MissionContrl.Entity;
using System.Windows;

namespace TestingPlatForm.MissionContrl.ViewModels
{
    public class MemoViewModel : BindableBase
    {

        private DateTime _date;
        private DateTime _time;
        private DateTime _dateEnd;
        private DateTime _timeEnd;
        private int scid = 1;
        private ObservableCollection<StackPanel> dynamicControls = new ObservableCollection<StackPanel>();
        private List<TextBox> textBoxes = new List<TextBox>();
        public delegate void ReceivedEventHandler(Dictionary<string, List<SateliteData>> keyValuePairs, string time);
        public event ReceivedEventHandler OnReceivedMessage;
        private readonly IEventAggregator _eventAggregator;
        #region
        public DateTime Date
        {
            get => _date;
            set => SetProperty(ref _date, value);
        }

        public DateTime Time
        {
            get => _time;
            set => SetProperty(ref _time, value);
        }

        public DateTime DateEnd
        {
            get => _dateEnd;
            set => SetProperty(ref _dateEnd, value);
        }

        public DateTime TimeEnd
        {
            get => _timeEnd;
            set => SetProperty(ref _timeEnd, value);
        }

        public int Scid
        {
            get { return scid; }
            set { scid = value; }
        }

        public ObservableCollection<StackPanel> DynamicControls
        {
            get { return dynamicControls; }
            set { SetProperty(ref dynamicControls, value); }
        }

        public List<TextBox> TextBoxes
        {
            get { return textBoxes; }
            set { textBoxes = value; }
        }

        #endregion
        private Dictionary<string, List<SateliteData>> _keyValues;

        public Dictionary<string, List<SateliteData>> keyValues
        {
            get { return _keyValues; }
            set
            {
                SetProperty(ref _keyValues, value);
                RaiseDictionaryTransferEvent();
            }
        }
        private Dictionary<string, List<EphData>> _EphDataDic;

        public Dictionary<string, List<EphData>> EphDataDic
        {
            get { return _EphDataDic; }
            set
            {
                SetProperty(ref _EphDataDic, value);
            }
        }

        public MemoViewModel(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;
            Date = DateTime.Now;
            Time = DateTime.Now;
            DateEnd = DateTime.Now;
            TimeEnd = DateTime.Now;
            keyValues = new Dictionary<string, List<SateliteData>>();
            EphDataDic = new Dictionary<string, List<EphData>>();
        }
        private void RaiseDictionaryTransferEvent()
        {
            _eventAggregator.GetEvent<DictionaryTransferEvent>().Publish(new DictionaryTransferEventArgs { Data = keyValues });
        }

        public ICommand AddCommand
        {
            get => new DelegateCommand(() =>
            {
                try
                {
                    foreach (StackPanel item in DynamicControls)
                    {
                        if (item.Name == "ttcs")
                        {
                            DynamicControls.Clear();
                            textBoxes.Clear();
                            scid = 1;
                            break;
                        }
                    }

                    var stackPanel = new StackPanel() { Orientation = Orientation.Horizontal, Margin = new System.Windows.Thickness(0, 10, 0, 0) };
                    var label = new Label() { Content = "SCID" + scid.ToString(), Width = 150 };
                    var TextBox = new TextBox() { Name = "SCID" + scid.ToString(), Width = 200 };
                    stackPanel.Children.Add(label);
                    stackPanel.Children.Add(TextBox);
                    scid++;
                    DynamicControls.Add(stackPanel);
                    textBoxes.Add(TextBox);

                }
                catch (Exception)
                {

                }
            });
        }

        public ICommand CreateCommand
        {
            get => new DelegateCommand(() =>
            {
                if (textBoxes.Count() >= 0)
                {
                    DynamicControls.Clear();
                    textBoxes.Clear();
                    var stackPanel1 = new StackPanel() { Name="ttcs", Orientation = Orientation.Horizontal, Margin = new System.Windows.Thickness(0, 10, 0, 0) };
                    var label1 = new Label() { Content = "卫星scId数组", Width = 150 };
                    var TextBox1 = new TextBox() { Name = "scIds", Width = 200 };
                    stackPanel1.Children.Add(label1);
                    stackPanel1.Children.Add(TextBox1);
                    DynamicControls.Add(stackPanel1);
                    textBoxes.Add(TextBox1);
                    var stackPanel2 = new StackPanel() { Orientation = Orientation.Horizontal, Margin = new System.Windows.Thickness(0, 10, 0, 0) };
                    var label2 = new Label() { Content = "测控站数组", Width = 150 };
                    var TextBox2 = new TextBox() { Name = "siteIds", Width = 200 };
                    stackPanel2.Children.Add(label2);
                    stackPanel2.Children.Add(TextBox2);
                    DynamicControls.Add(stackPanel2);
                    textBoxes.Add(TextBox2);
                    var stackPanel3 = new StackPanel() { Orientation = Orientation.Horizontal, Margin = new System.Windows.Thickness(0, 10, 0, 0) };
                    var label3 = new Label() { Content = "起跟角度,整数", Width = 150 };
                    var TextBox3 = new TextBox() { Name = "minElev", Width = 200, Text = "23" };
                    stackPanel3.Children.Add(label3);
                    stackPanel3.Children.Add(TextBox3);
                    DynamicControls.Add(stackPanel3);
                    textBoxes.Add(TextBox3);
                    var stackPanel4 = new StackPanel() { Orientation = Orientation.Horizontal, Margin = new System.Windows.Thickness(0, 10, 0, 0) };
                    var label4 = new Label() { Content = "轨道类型", Width = 150 };
                    var TextBox4 = new TextBox() { Name = "type", Width = 200, Text = "4" };
                    stackPanel4.Children.Add(label4);
                    stackPanel4.Children.Add(TextBox4);
                    DynamicControls.Add(stackPanel4);
                    textBoxes.Add(TextBox4);

                }
            });
        }

        public ICommand CutCommand
        {
            get => new DelegateCommand(() =>
            {
                if (DynamicControls.Count > 0)
                {
                    int id = --scid - 1;
                    DynamicControls.RemoveAt(id);
                    textBoxes.RemoveAt(id);
                }
            });
        }

        public ICommand PutSPTCommand
        {
            get => new DelegateCommand(() =>
            {
                try
                {
                    try
                    {
                        EphDataDic.Clear(); 
                        JsonEphemerisData jsonEphemerisData = new JsonEphemerisData();
                        jsonEphemerisData.startTime = Date.ToString("yyyy-MM-dd HH:mm:ss");
                        jsonEphemerisData.endTime = DateEnd.ToString("yyyy-MM-dd HH:mm:ss");
                        jsonEphemerisData.orbType = 1;
                        jsonEphemerisData.predType = 4;
                        List<int> scids = new List<int>();
                        foreach (var item in textBoxes)
                        {
                            scids.Add(int.Parse(item.Text?.ToString()));
                        }
                        jsonEphemerisData.scIds = scids;
                        string templete = JsonConvert.SerializeObject(jsonEphemerisData);
                        HttpService httpService = new HttpService(GlobalEntity.configData.OPS_IP, "");
                        var res = httpService.POST("ops/out-api/Ephemeris", templete).Result;
                        EphemerisData ephemerisData = JsonConvert.DeserializeObject<EphemerisData>(res);
                        if (ephemerisData.code == 200 && ephemerisData.data != null)
                        {
                            List<DataInfo> dataInfos = ephemerisData.data;
                            foreach (DataInfo dataInfo in dataInfos)
                            {
                                List<EphData> ephDatas = new List<EphData>();
                                foreach (var item in dataInfo.infos)
                                {
                                    EphData ephData = new EphData();
                                    ephData.j2000X = item.j2000X;
                                    ephData.j2000Y = item.j2000Y;
                                    ephData.j2000Z = item.j2000Z;
                                    ephData.j2000Vx = item.j2000Vx;
                                    ephData.j2000Vy = item.j2000Vy;
                                    ephData.j2000Vz = item.j2000Vz;
                                    ephData.instantTime = DateTime.Parse(item.instantTime);
                                    ephDatas.Add(ephData);
                                }
                                EphDataDic[dataInfo.scId.ToString()] = ephDatas;
                                
                            }
                        }
                        ControlTxT controlTxT = new ControlTxT();
                        foreach (var item in EphDataDic)
                        {
                            string name = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss_") + item.Key;
                            controlTxT.insertTXT(item.Value,name);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
                catch (Exception)
                {
                }
            });
        }

        public ICommand GetSPTCommand
        {
            get => new DelegateCommand(() =>
            {
                try
                {
                    keyValues.Clear();
                    JsonPostData jsonPostData = new JsonPostData();
                    jsonPostData.startTime = Date.ToString("yyyy-MM-dd HH:mm:ss");
                    jsonPostData.endTime = DateEnd.ToString("yyyy-MM-dd HH:mm:ss");
                    jsonPostData.satNumber = scid - 1;
                    List<int> scids = new List<int>();
                    foreach (var item in textBoxes)
                    {
                        scids.Add(int.Parse(item.Text?.ToString()));
                    }
                    jsonPostData.scIds = scids;
                    string templete = JsonConvert.SerializeObject(jsonPostData);
                    HttpService httpService = new HttpService(GlobalEntity.configData.OPS_IP, "");
                    var res = httpService.POST("ops/out-api/spt", templete).Result;
                    OpsData opsData = JsonConvert.DeserializeObject<OpsData>(res);
                    if (opsData.code == 200 && opsData.data != null)
                    {
                        List<SCIDInfo> sCIDInfos = opsData.data;
                        foreach (SCIDInfo sCIDInfo in sCIDInfos)
                        {
                            List<SateliteData> sateliteDatas = new List<SateliteData>();
                            foreach (var item in sCIDInfo.infos)
                            {
                                SateliteData sateliteData = new SateliteData();
                                sateliteData.utcSecond = item.accSecond;
                                sateliteData.sptSecond = item.accSecondBd;
                                sateliteData.delta_a = item.deltA / (4.249 * Math.Pow(10, -3));
                                sateliteData.e = item.ecc / (1.431 * Math.Pow(10, -8));
                                sateliteData.delta_i = item.inc / 3.1415926 / Math.Pow(2, -27);
                                sateliteData.OMEGA0 = (item.raan - 2 * 3.1415926) / 3.1415926 / Math.Pow(2, -27);
                                sateliteData.omega = (item.aop - 2 * 3.1415926) / 3.1415926 / Math.Pow(2, -27);
                                sateliteData.M0 = (item.meanAnomaly - 2 * 3.1415926) / 3.1415926 / Math.Pow(2, -27);
                                sateliteDatas.Add(sateliteData);
                            }
                            keyValues[sCIDInfo.scId.ToString()] = sateliteDatas;
                            //if (sCIDInfo.scId.ToString() == "4096")
                            //{
                            //    keyValues["257"] = sateliteDatas;
                            //}
                            //else if (sCIDInfo.scId.ToString() == "4098")
                            //{
                            //    keyValues["259"] = sateliteDatas;
                            //}
                            //else if (sCIDInfo.scId.ToString() == "4108")
                            //{
                            //    keyValues["279"] = sateliteDatas;
                            //}
                            //else if (sCIDInfo.scId.ToString() == "8193")
                            //{
                            //    keyValues["1281"] = sateliteDatas;
                            //}
                        }
                    }
                    ControlTxT controlTxT = new ControlTxT();
                    controlTxT.insertTXT(keyValues, "SPT_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
                }
                catch (Exception)
                {
                }
            });
        }

        public ICommand GetListCommand
        {
            get => new DelegateCommand(() =>
            {
                try
                {
                    JsonAlmanacdata jsonAlmanacdata = new JsonAlmanacdata();
                    jsonAlmanacdata.satNumber = scid - 1;
                    List<int> scids = new List<int>();
                    foreach (var item in textBoxes)
                    {
                        scids.Add(int.Parse(item.Text?.ToString()));
                    }
                    jsonAlmanacdata.scIds = scids;
                    string templete = JsonConvert.SerializeObject(jsonAlmanacdata);
                    HttpService httpService = new HttpService(GlobalEntity.configData.OPS_IP, "");
                    var res = httpService.POST("/out-api/almanac", templete).Result;
                    OpsAlmanacData opsAlmanacData = JsonConvert.DeserializeObject<OpsAlmanacData>(res);
                    if (opsAlmanacData.code == 200)
                    {
                        ControlTxT controlTxT = new ControlTxT();
                        controlTxT.insertTXT(opsAlmanacData.data, templete);
                    }
                }
                catch (Exception)
                {
                }
            });
        }

        public ICommand GetProtestCommand
        {
            get => new DelegateCommand(() =>
            {
                try
                {
                    forecastData forecastData = new forecastData();
                    forecastData.passTimeBegin = Date.ToString("yyyy-MM-dd HH:mm:ss");
                    forecastData.passTimeEnd = DateEnd.ToString("yyyy-MM-dd HH:mm:ss");

                    string scids = textBoxes[0].Text?.ToString();
                    string[] strings = scids.Split(",");
                    List<int> scIds  = new List<int>();
                    foreach (string s in strings) { scIds.Add(int.Parse(s)); }
                    forecastData.scIds = scIds;

                    string siteids = textBoxes[1].Text?.ToString();
                    string[] strings1 = siteids.Split(",");
                    List<int> siteIds = new List<int>();
                    foreach (string s in strings1) { siteIds.Add(int.Parse(s)); }
                    forecastData.siteIds = siteIds;

                    forecastData.minElev = int.Parse(textBoxes[2].Text?.ToString());
                    forecastData.type = int.Parse(textBoxes[3].Text?.ToString());
                    string templete = JsonConvert.SerializeObject(forecastData);
                    HttpService httpService = new HttpService(GlobalEntity.configData.OPS_IP, "");
                    //var res = httpService.POST("ttcs/pass/forecast", templete).Result;
                    string postTemplete = "ttcs/pass/forecast?passTimeBegin=" + forecastData.passTimeBegin + "&passTimeEnd=" + forecastData.passTimeEnd + "&scIds=" + textBoxes[0].Text + "&siteIds=" + textBoxes[1].Text + "&minElev=" + textBoxes[2].Text + "&type=" + textBoxes[3].Text;
                    var res = httpService.POST(postTemplete, "1").Result;
                    ttcsData ttcsData = JsonConvert.DeserializeObject<ttcsData>(res);
                    if (ttcsData.code == 200 && ttcsData.data != null)
                    {
                        List<PassInfo> sCIDInfos = ttcsData.data;
                        ControlExcel controlExcel = new ControlExcel();
                        controlExcel.insertExcel(DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"), sCIDInfos);
                    }
                }
                catch (Exception)
                {
                }
            });
        }

    }
}
